import functools
from functools import wraps

import sqlalchemy
# from civen_license import HardwareInfoCollector, MachineCodeGenerator, LicenseVerifier, LicenseException

from app.api.response import Response
from app.api.status import Status
from app.datatype import DeclBase
from app.datatype.model_config import ModelConfigListMdl, ModelConfig, ModelConfigGet, CodeAuthorizationMdl

from app.initializer import g
from app.utils import db_async
from app.utils.db_async import format_all


class ModelConfigListBiz(ModelConfigGet):

    async def lst(self):
        """
        获取模型配置列表
        """

        sql_base = (
            f"select * from model_config where is_deleted = 0 ")
        params = {}

        sql = sqlalchemy.text(sql_base)
        async with g.db_async_session() as session:
            result = await session.execute(sql, params)
            rows = result.fetchall()
            return await format_all(rows, ModelConfigListMdl.response_fields())


class ModelConfigBiz(ModelConfigListMdl):
    """
    创建模型配置
    """

    async def create(self):
        async with g.db_async_session() as session:
            return await db_async.create(
                session=session,
                model=ModelConfig,
                data={

                    "model_name": self.model_name,
                    "model_url": self.model_url,
                    "model_api_key": self.model_api_key,
                    "model_type": self.model_type,
                    "is_deleted": 0,  # 默认未删除
                }
            )

    async def update(self):
        async with g.db_async_session() as session:
            return await db_async.update(
                session=session,
                model=ModelConfig,
                data={
                    "model_name": self.model_name,
                    "model_url": self.model_url,
                    "model_api_key": self.model_api_key,
                    "model_type": self.model_type,
                },
                filter_by={"id": self.id},
            )

    async def delete(self):
        async with g.db_async_session() as session:
            return await db_async.update(
                session=session,
                model=ModelConfig,
                data={
                    "is_deleted": 1,  # 默认未删除
                },
                filter_by={"id": self.id},
            )


def get_model_config( model_name: str) ->ModelConfigListMdl :

    sql_base = (
        f"select * from model_config where is_deleted = 0 and model_name = :model_name")
    params = {}
    params["model_name"] = f"{model_name}"
    sql = sqlalchemy.text(sql_base)
    with g.db_session() as session:
        result =  session.execute(sql, params)
        rows = result.fetchall()
    if not rows:
        return ModelConfigListMdl()
    model_config_list = [
        ModelConfigListMdl(**row._mapping) for row in rows
    ]
    if not model_config_list:
        return ModelConfigListMdl()
    model_config_one = model_config_list[0]

    # print('!!!!aaaaaaaaaaaaaaaaaaaa!!!!!!!!!!!!!!!!!!!!')
    # print(model_config_one)
    # print(model_config_one.model_api_key)
    return model_config_one


# def require_license(feature_name=""):
#     """授权检查装饰器"""
#     def decorator(func):
#         @functools.wraps(func)
#         async def wrapper(*args, **kwargs):
#             # 创建验证器
#             hardware_collector = HardwareInfoCollector()
#             machine_code_generator = MachineCodeGenerator("rag-core", hardware_collector)
#             license_verifier = LicenseVerifier(machine_code_generator)
#
#             # 检查授权
#             if not license_verifier.validate_local_license():
#                 return Response.failure(msg="需要授权", status=Status.UNAUTHORIZED_ERROR)
#
#             return await func(*args, **kwargs)
#         return wrapper
#     return decorator

